﻿namespace ImageViewerWPF
{
    using System.Collections.Generic;
    using System.Text;

    public static class TagConversion
    {
        public static char DatabaseTagSeparator = ',';

        public static string FromFileToTable(string fileTagString)
        {
            if (string.IsNullOrEmpty(fileTagString))
            {
                return "";
            }

            string[] tags = fileTagString.Split(new char[] { ',' });

            List<string> cleanTags = new List<string>();

            foreach (string tag in tags)
            {
                string trimTag = tag.Trim();
                if (trimTag != "" && !trimTag.Contains("|"))
                {
                    cleanTags.Add(trimTag);
                }
            }

            if (cleanTags.Count == 0)
            {
                return "";
            }

            StringBuilder tableStringBuilder = new StringBuilder();

            tableStringBuilder.Append(DatabaseTagSeparator);

            foreach (string tag in cleanTags)
            {
                tableStringBuilder.Append(tag);
                tableStringBuilder.Append(DatabaseTagSeparator);
            }

            return tableStringBuilder.ToString();
        }

        public static string FromTableToFile(string tableTagString)
        {
            if (string.IsNullOrEmpty(tableTagString))
            {
                return "";
            }

            string[] tags = tableTagString.Split(new char[] {DatabaseTagSeparator});

            List<string> cleanTags = new List<string>();

            foreach (string tag in tags)
            {
                string trimTag = tag.Trim();

                if (trimTag != "" && !trimTag.Contains("|"))
                {
                    cleanTags.Add(trimTag);
                }
            }

            StringBuilder fileStringBuilder = new StringBuilder();

            int addedTags = 0;
            foreach (string tag in cleanTags)
            {
                fileStringBuilder.Append(tag.ToLowerInvariant());

                addedTags++;
                if (addedTags < cleanTags.Count)
                {
                    fileStringBuilder.Append(", ");
                }
            }

            return fileStringBuilder.ToString();
        }
    }
}